package belf.migrate.engine.job.structure.helper;

import belf.migrate.api.common.DatabaseCompatibility;
import belf.migrate.api.common.DatabaseIdentifier;
import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.exception.DDLException;
import belf.migrate.api.table.schema.Catalog;
import belf.migrate.api.table.schema.TablePath;
import belf.migrate.api.table.schema.UserDefFunction;
import belf.migrate.api.taskconf.JobContext;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.api.type.LogLevelType;
import belf.migrate.api.util.EngineConf;
import belf.migrate.api.util.PostLog;
import belf.migrate.core.exception.BelfRuntimeException;
import belf.migrate.engine.ddl.BaseDDLConvert;
import belf.migrate.engine.ddl.function.FunctionConvertFactory;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.JobResultItem;
import belf.migrate.api.taskconf.Task;
import belf.migrate.api.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

import static belf.migrate.api.job.JobCode.*;

@Slf4j
public class CreateFunctionTool extends SqlTransformTool {
    public CreateFunctionTool(Job job) {
        super(job);
    }

    public CreateFunctionTool(Job job, JobContext jobContext) {
        super(job, jobContext);
    }

    @Override
    public JobResult run() {
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建函数开始！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResult jobResult = new JobResult(SUCCESS, "创建选中的函数成功");
        Catalog sourceCatalog = jobContext.getSourceCatalog();
        Catalog sinkCatalog = jobContext.getSinkCatalog();
        String sourceSchema = jobContext.getValidSourceDatabase();

        // FIXME: 函数名称暂不需要转换，因此此处暂用源端的限定规则
        List<String> functionNames = job.getMissions(); //用户是否指定了要创建的函数的名字？
        try {
            List userDefFunctions = sourceCatalog.listFunctions(sourceSchema, functionNames);
            if (!CollectionUtils.isEmpty(userDefFunctions)) {
                transform(userDefFunctions, jobResult);
            }
        } catch (CatalogException e) {
            e.printStackTrace();
        }
        if (jobResult.getFailtures() > 0) {
            jobResult.setCode(CREATE_FUNCTION_ERROR);
            jobResult.setMessage("创建选中的函数失败");
            log.error("Create Some Functions Of {} Failed.", jobContext.getValidSinkDatabase());
        } else {
            log.info("Create All Functions Of {} Successfully.", jobContext.getValidSinkDatabase());
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建函数结束！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        return jobResult;
    }

    @Override
    protected JobResultItem process(Object object) {
        UserDefFunction userDefFunction = (UserDefFunction)object;
        TablePath tablePath = TablePath.of(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                userDefFunction.getFunctionName(),
                getSinkQualifiersModel());
        JobResultItem jobResultItem = new JobResultItem(userDefFunction.getFunctionName(), tablePath.getCaseTableName(), SUCCESS, "创建函数 " + userDefFunction.getFunctionName() + "成功");
        jobResultItem.setType(DbObjectType.FUNCTION.getTypeName());
        String startTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        jobResultItem.setStartTime(startTime);

        String sourceDdl = userDefFunction.getDdl();

        String promptTempalate = """
                    请将以下%s创建函数的SQL语句转为%s创建函数的SQL语句：\n
                    %s\n
                    %s
                    """;
        String srcDbCatalog = DatabaseIdentifier.name(jobContext.getTaskConf().getSourceConf().getCatalogName());
        String targetDbCatalog = DatabaseIdentifier.name(jobContext.getTaskConf().getSinkConf().getCatalogName());
        String requirement = PromtHelper.requirement(jobContext.getTaskConf().getSourceConf().getCatalogName(),
                jobContext.getTaskConf().getSinkConf().getCatalogName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                getSinkQualifiersModel(),
                DbObjectType.FUNCTION);
        //是否启用数据库的语法兼容性？比如达梦极大兼容Oracle
        boolean dbCompatible = EngineConf.getInstance().getBoolean("llm.enable.db.compatible");
        String prompt = String.format(promptTempalate,
                srcDbCatalog,
                dbCompatible? DatabaseCompatibility.name(jobContext.getTaskConf().getSinkConf().getCatalogName()):targetDbCatalog,
                sourceDdl,
                requirement);
        log.info("转换函数的提示词：\n{}", prompt);

        String sinkDDL = null;
        SqlResponse sqlResponse = null;
        try {
            sqlResponse = SqlAgent.post(jobContext.getTaskConf().getAiModel(), prompt);
            if (null != sqlResponse) {
                sinkDDL = sqlResponse.getSql();
                jobContext.getSinkCatalog().executeDdl(tablePath, sinkDDL);
                jobResultItem.setSinkDdl(sinkDDL);
                log.info("Create Function successfully:\n{}", sinkDDL);
            }

        } catch (DDLException e) {
            log.error("Function create ddl: \n{}", sinkDDL);
            e.printStackTrace();
            String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    String.format("创建函数 %s 失败, SQL错误：%s", userDefFunction.getFunctionName(), e.getCause().getMessage()),
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());

            String errorTips = null;
            if (sqlResponse != null) {
                // 返回大模型给出的sql转化理由
                errorTips = String.join("\n", sqlResponse.getReasons());
            }
            return new JobResultItem(userDefFunction.getFunctionName(),
                    tablePath.getCaseTableName(),
                    CREATE_FUNCTION_ERROR,
                    String.format("创建函数 %s 失败, SQL错误：%s", userDefFunction.getFunctionName(), e.getCause().getMessage()),
                    ExceptionUtils.toString(e.getCause()),
                    DbObjectType.FUNCTION.getTypeName(),
                    startTime,
                    endTime,
                    userDefFunction.getDdl(),
                    sinkDDL,
                    errorTips);
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建函数 " + userDefFunction.getFunctionName() + "成功",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        jobResultItem.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        return jobResultItem;
    }
}
